<?php
class marker_model extends CI_Model{
	
	function __construct(){
		parent::__construct();
		$this->load->database();
	}
	
	/**
	 * 	Agregar una marcador
	 * 	@param array $params			Parametros Post enviados
	 * 
	 * 	@return Array
	 */
	public function add($params){
		$this->load->model('user_model');
		$res = $this->user_model->getIdUserToken($params);
		if($res->num_rows() > 0){
			//informacion del usuario
			$data_usr = $res->row_array();
			$values = array(
				'id_usuario' 	=> $data_usr['id_usuario'],
				'titulo' 		=> $params['title'],
				'url' 			=> $params['url'],
				'id_obj' 		=> $params['obj'],
				'tipo' 			=> $params['type']
			);
			$this->db->insert('marcadores', $values);
		
			return array('id' => $this->db->insert_id());
		}
		return false;
	}
	
	/**
	 * Elimina un marcador
	 */
	public function delete($params){
		$bann = $this->exist('marcadores', array('id_marcador' => $params['marker']), TRUE);
		if(is_object($bann)){
			
			$this->db->delete('marcadores', array('id_marcador' => $params['marker']));
			
			return array('id' => $params['marker']);
		}
		return FALSE; //no existe el marcador
	}
	
	/**
	 * Obtener lista de banners
	 */
	public function get($params){
		$res = $this->db
			->select('
				id_marcador AS id,
				id_usuario AS user,
				titulo AS title, 
				url,
				id_obj AS obj,
				tipo AS type')
			->from('marcadores')
			->where("id_usuario = ".$params['usr_info']['id_usuario'])
		->get();
		
		$respon = array();
		foreach ($res->result_array() as $value) {
			if($value['type'] == '1'){ //capitulo
				$res1 = $this->db
					->select('
						st.url_poster_small')
					->from('series_capitulos AS sc')
						->join('series_temporadas AS st', 'st.id_temporada = sc.id_temporada', 'inner')
					->where("sc.id_capitulo = ".$value['obj'])
				->get();
			}else{ //pelicula
				$res1 = $this->db
					->select('
						url_poster_small')
					->from('peliculas')
					->where("id_pelicula = ".$value['obj'])
				->get();
			}
			
			$value['img'] = $res1->row()->url_poster_small;
			$respon[] = $value;
			
			$res1->free_result();
		}
		
		return array('markers' => $respon);
	}


	
	private function exist($table, $sql, $return_res=false){
		$res = $this->db->get_where($table, $sql);
		if($res->num_rows() > 0){
			if($return_res)
				return $res->row();
			return TRUE;
		}
		return FALSE;
	}
}